# coding=utf8
# 导入已存在的项目的工程信息

from app import create_app
from app.modules.project.models import ProjectInfo, ProjectOutBeetle
from app.extensions import db
from app.modules.common.utils import DbCommit
from app.modules.project import TRUNK_LIST
from app.modules.projectPlan.models import ProjectPlanInfo

application = create_app(flask_config = 'local')


def addPlanPro(_plan_id, _trunk_name, _project_name, _svn_url, _branch_num, _package_name):
    print 'add %s ' % _project_name
    _proinfo = ProjectInfo.query.filter_by(trunk_name = _trunk_name, plan_id = _plan_id).first()
    if _proinfo is None:
        _isOnBeetle = '0'
        if ProjectOutBeetle.query.filter_by(trunk_name = _trunk_name).first() is not None:
            _isOnBeetle = '1'

        db.session.add(
            ProjectInfo(project_name = _project_name, plan_id = _plan_id, trunk_name = _trunk_name, vcs_path = _svn_url,
                        local_path = getLocalPath(_trunk_name, _project_name), branch_num = _branch_num,
                        isOnBeetle = _isOnBeetle, project_status = 'PRO_DEVELOPING',
                        package_type = TRUNK_LIST[_trunk_name], package_name = _package_name))
        _rtn = DbCommit(cleanPro = True)
        print 'add %s . return %s ' % (_project_name, _rtn)


def getLocalPath(_trunk_name, _project_name):
    return '/usr/local/Beetle/projects/%s/%s/' % (_trunk_name, _project_name)


def main(_zentao_id, _list):
    with application.app_context():
        _plan = ProjectPlanInfo.query.filter_by(zt_id = _zentao_id).first()
        if _plan is None:
            print '项目不存在 %s' % _zentao_id
            return

        _plan_id = _plan.plan_id

        for _pro in _list:
            addPlanPro(_plan_id, _pro['trunk_name'], _pro['project_name'], _pro['svn_url'], _pro['branch_num'],
                       _pro['package_name'])
        pass


if __name__ == '__main__':
    _zentao_id = '1338'

    _list = [{
        'trunk_name': 'CSI',
        'project_name': 'CSI',
        'svn_url': 'https://192.168.130.6:8443/svn/winit2.0/cwm-psi/trunk',
        'branch_num': '1.1.1',
        'package_name': 'CSI'
    }]

    main(_zentao_id, _list)
